<?php
namespace app\zftpay\service;
use alipay\AlipayTradeOrderSettleQueryRequest;
use alipay\AlipayTradeOrderSettleRequest;
use alipay\AlipayTradeRoyaltyRelationBindRequest;
use alipay\AntMerchantExpandIndirectZftorderQueryRequest;
use alipay\AopClient;

use alipay\AlipayOpenAuthTokenAppRequest;    //查询物业token


use alipay\AlipaySystemOauthTokenRequest;//换取授权访问令牌
use alipay\AlipayTradeCreateRequest;//生成订单
use alipay\AlipayTradeCloseRequest;
use stdClass;
use think\Db;
use think\Log;

class apiService{
    const PRIKEYPATH = '/www/wwwroot/zaozao/pathappid/zft/prikey.txt';//私钥路径
    const PUBKEYPATH = '/www/wwwroot/zaozao/pathappid/zft/pubkey.txt';//支付宝公钥路径


    private $app_id;//支付宝分配给开发者的应用
    private $method;//接口名称
    private $format;//仅支持JSON  no
    private $charset = 'UTF-8';//请求使用的编码格式，如utf-8,gbk,gb2312等
    private $sign_type = 'RSA2';//商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
    private $sign;//商户请求参数的签名串  no
    private $timestamp;//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
    private $version = '1.0';//调用的接口版本，固定为：1.0
    private $app_auth_token;//详见应用授权概述 no
    private $biz_content;//请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递，具体参照各产品快速接入文档

    private $apiUrl; // no


    public function getPublicContent() {
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021003127655947';
        $aop->rsaPrivateKey = file_get_contents(self::PRIKEYPATH);//私钥路径
        $aop->alipayrsaPublicKey= file_get_contents(self::PUBKEYPATH);//支付宝公钥路径
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        return $aop;
    }
    
    public function getAppAuthToken($code) {
        $aop = $this->getPublicContent();
        $request = new AlipayOpenAuthTokenAppRequest();
        $request->setBizContent("{" .
            "    \"grant_type\":\"authorization_code\"," .
            "    \"code\":\"$code\"" .
            "  }");
        $response = $aop->execute($request);
        dump($response);exit();
    }

    //XIOA
    public function xcxgetPublicContent(){
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018110562021261';
        $aop->rsaPrivateKey = file_get_contents(self::XCXPRIKEYPATH);//私钥路径
        $aop->alipayrsaPublicKey= file_get_contents(self::XCXPUBKEYPATH);//支付宝公钥路径
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        return $aop;
    }

    //小程序换取授权访问令牌
    public function xcxoauthToken($code){
        $aop = $this->xcxgetPublicContent();
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $request->setRefreshToken('');
        $result = $aop->execute ($request);
        if(property_exists($result,'error_response')){
            $responseNode = 'error_response';
        }else{
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";   
        }
        return $result->$responseNode;
    }

    //分账关系绑定
    public function royaltyRelationBind($data){
        $data = json_decode($data);
        $aop = $this->getPublicContent();
        $request = new AlipayTradeRoyaltyRelationBindRequest ();
        $request->setBizContent("{" .
            "  \"receiver_list\":[" .
            "    {" .
            "      \"type\":\"$data->type\"," .
            "      \"account\":\"$data->account\"," .
            "      \"name\":\"$data->name\"," .
            "      \"memo\":\"$data->memo\"" .
            "    }" .
            "  ]," .
            "  \"out_request_no\":\"$data->out_request_no\"" .
            "}");
        $token = $data->token;
        $result = $aop->execute ($request, null, $token);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            return $result->$responseNode->community_id;
        } else {
            return ['error' => $result->$responseNode->sub_msg];
        }
    }

    //分账关系解绑
    public function royaltyRelationUnbind($data){

    }
    //分账关系查询
    public function royaltyRelationBatchquery($data){

    }

    //生成订单
    public  function create($data){
        $data = json_decode($data);

        $aop = $this->getPublicContent();
        $request = new AlipayTradeCreateRequest ();
        $object = new stdClass();

        /*$request->setBizContent("{" .
            "\"out_trade_no\":\"$data->out_trade_no\"," .
            "\"total_amount\":$data->total_amount," .
            "\"subject\":\"$data->subject\"," .
            "\"buyer_id\":\"$data->buyer_id\"," .
            "\"sell_id\":\"$data->sell_id\"," .
            "\"extend_params\":{".
            "\"sys_service_provider_id\":\"2088131393104892\"".
            "},".
            "\"timeout_express\":\"100m\"" .
            "  }");*/
        $object->out_trade_no=$data->out_trade_no;
        $object->total_amount=$data->total_amount;
        $object->subject=$data->subject;
        $object->buyer_id=$data->buyer_id;
        //$object->sell_id=$data->sell_id;

        $extendParams = [
             'sys_service_provider_id'=>'2088131393104892',
        ];
        $object->extend_params = $extendParams;

        $settleInfo = [
            'settle_detail_infos'=>[
                 [
                     'trans_in_type'=>$data->settle_detail_info->trans_in_type,
                     'trans_in'=>$data->settle_detail_info->trans_in,
                     'amount'=>$data->settle_detail_info->amount,
                 ]
            ]
        ];
        $object->settle_info = $settleInfo;

        //二级商户编号
        $subMerchant = [
            'merchant_id'=>$data->merchant_id,
        ];
        $object->sub_merchant = $subMerchant;
        $object->product_code='FACE_TO_FACE_PAYMENT';
        $json = json_encode($object);

        //Log::write($json);
        $request->setBizContent($json);
        $request->setNotifyUrl($data->notifyUrl);
        $result = $aop->execute ($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    //银行卡收款
    public  function create2($data){
        $data = json_decode($data);

        $aop = $this->getPublicContent();
        $request = new AlipayTradeCreateRequest ();
        $object = new stdClass();


        $object->out_trade_no=$data->out_trade_no;
        $object->total_amount=$data->total_amount;
        $object->subject=$data->subject;
        $object->buyer_id=$data->buyer_id;
        //$object->sell_id=$data->sell_id;

        $extendParams = [
            'sys_service_provider_id'=>'2088131393104892',
        ];
        $object->extend_params = $extendParams;

        $settleInfo = [
            'settle_detail_infos'=>[
                [
                    'trans_in_type'=>$data->settle_detail_info->trans_in_type,
                    'trans_in'=>$data->settle_detail_info->trans_in,
                    'amount'=>$data->settle_detail_info->amount,
                ]
            ]
        ];
        $object->settle_info = $settleInfo;

        //二级商户编号
        $subMerchant = [
            'merchant_id'=>'2088610162385563',
        ];
        $object->sub_merchant = $subMerchant;
        $object->product_code='FACE_TO_FACE_PAYMENT';
        $json = json_encode($object);

        Log::write($json);
        $request->setBizContent($json);
        $request->setNotifyUrl($data->notifyUrl);
        $result = $aop->execute ($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    //返佣结算
    public function settle($data){
        $data = json_decode($data);
        $aop = $this->getPublicContent();
        $request = new AlipayTradeOrderSettleRequest ();
        $object = new stdClass();


        $object->out_request_no=$data->out_trade_no;
        $object->trade_no=$data->trade_no;
        $royalty_parameters = [
            [
                'royalty_type'=>$data->royalty_parameters->royalty_type,//分账类型
                'trans_in_type'=>$data->royalty_parameters->trans_in_type,//收入方账户类型
                'trans_in'=>$data->royalty_parameters->trans_in,//收入方账户\
                'amount'=>$data->royalty_parameters->amount,//分账金额
            ],
        ];


        $object->royalty_parameters = $royalty_parameters;
        $json = json_encode($object);
        Log::write($json);
        $request->setBizContent($json);
        /*$royalty_parameters=$data->royalty_parameters;
        $str="{" .
                "\"out_request_no\":\"$data->out_trade_no\"," .
                "\"trade_no\":\"$data->trade_no\"," .
                "\"royalty_parameters\":[" .
                    "{" .
                        "\"royalty_type\":\"$royalty_parameters->royalty_type\"," .
                        "\"trans_out\":\"$royalty_parameters->trans_out\"," .
                        "\"trans_out_type\":\"$royalty_parameters->trans_out_type\"," .
                        "\"trans_in_type\":\"$royalty_parameters->trans_in_type\"," .
                        "\"trans_in\":\"$royalty_parameters->trans_in\"," .
                        "\"amount\":$royalty_parameters->amount" .
                    "}" .
                "]" .
            "}";
        Log::write($str);
        $request->setBizContent($str);*/
        $result = $aop->execute ($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    public function settleQuery($data){
        $data = json_decode($data);
        $aop = $this->getPublicContent();
        $request = new AlipayTradeOrderSettleQueryRequest ();
        $object = new stdClass();
        $object->settle_no=$data->settle_no;
        $json = json_encode($object);

        $request->setBizContent($json);
        $result = $aop->execute ($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    public function zftorderQuery($data){
        $data = json_decode($data);
        $aop = $this->getPublicContent();
        $request = new AntMerchantExpandIndirectZftorderQueryRequest ();
        $request->setBizContent("{" .
            "\"external_id\":\"$data->external_id\"" .
            "  }");
        $result = $aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }
}